package taewanme.gae.bookmark.dao;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import taewanme.gae.bookmark.model.User;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Repository("userDao")
public class UserDaoJDOImpl {
private Logger logger = LoggerFactory.getLogger(UserDaoJDOImpl.class);
	
	@Autowired
	private PersistenceManagerFactory pmf;
	
	public User get(String email){
			Key key = KeyFactory.createKey(User.class.getSimpleName(), email);
			return get(key);
	}
	
	public User get(Key key){
		PersistenceManager pm = null;
		try{
			pm = pmf.getPersistenceManager();
			
			User retrivedUser = pm.getObjectById(User.class, key);
			User detached = pm.detachCopy(retrivedUser);
			
			return detached;
		}finally{
			if(pm!=null) pm.close();
		}
	}

	
	public User save(User user){
		PersistenceManager pm = null;
		try{
			String mail = user.getMail();
			
			Key key = KeyFactory.createKey(User.class.getSimpleName(), mail);
			user.setKey(key);
			pm = pmf.getPersistenceManager();
			
			User savedUser = pm.makePersistent(user);
			User detached = pm.detachCopy(savedUser);
			
			return detached;
		}finally{
			if(pm!=null) pm.close();
		}
	}
	
	public void remove(String mail){
		PersistenceManager pm = null;
		try{
			User user = get(mail);
			pm = pmf.getPersistenceManager();
			pm.deletePersistent(user);
		}finally{
			if(pm!=null) pm.close();
		}
	}

	
	
}
